<?php
// $Id$

/**
 * Controller_Systemsetting 控制器
 */
class Controller_Systemsetting extends Controller_Abstract
{

	function actionIndex()
	{
        // 为 $this->_view 指定的值将会传递数据到视图中
		# $this->_view['text'] = 'Hello!';
	}

    function timespanFormat($seconds)
    {
        $days = floor($seconds / 86400);
        if ($days > 0)
        {
            $seconds -= $days * 86400;
        }
        $hours = floor($seconds / 3600);
        if ($days > 0 || $hours > 0)
        {
            $seconds -= $hours * 3600;
        }
        $minutes = floor($seconds / 60);
        if ($days > 0 || $hours > 0 || $minutes > 0)
        {
            $seconds -= $minutes * 60;
        }
        return sprintf('%s 天 %s 小时，%s 分 %s 秒', (string) $days, (string) $hours, (string) $minutes, (string) $seconds);
    }

    function getRealSize($size)
    {
        if ($size < 1024)
        {
            return $size.' Byte';
        }
        if ($size < 1048576)
        {
            return round($size / 1024, 2).' KB';
        }
        if ($size < 1073741824)
        {
            return round($size / 1048576, 2).' MB';
        }
        if ($size < 1099511627776)
        {
            return round($size / 1073741824, 2).' GB';
        }
    }
    function actionDatabaseManagement()
    {
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }
        $cur_user = $this->_app->currentUserObject();

        if($cur_user->permission_id != 1)
        {
            return $this->_redirect(url('default/index'));
        }
        require_once ('table.inc.php');
        require_once ('MySQL.class.php');
        $DB = new MySQL('localhost', 's445449db0', '121511lyz', 's445449db0', 0);
        
        $database = $result = array();            
        $database['version'] = $DB->db_version();
        $query = $DB->db_query('SHOW STATUS');
        while ($rs = $DB->fetch_all($query))
        {
            if ((strpos(strtolower($rs['Variable_name']), 'uptime')) !== FALSE)
            {
                $database['runtime'] = $this->timespanFormat($rs['Value']);
                break;
            }
        }
        $query = $DB->db_query('SHOW TABLE STATUS');


        $tianyi_tables = $othertable = $result = array();
        $tianyi_tablesnum = $tianyi_rownum = $tianyi_totalsize = $othertablenum = $otherrownum = $othertotalsize = 0;
        while ($rs = $DB->fetch_all($query))
        {
            if (in_array($rs['Name'], $ty_tables))
            {
                $tianyi_rownum += $rs['Rows'];
                $tianyi_totalsize += ($rs['Data_length'] + $rs['Index_length'] + $rs['Data_free']);
                $rs['Type'] = isset($rs['Type']) ? $rs['Type'] : $rs['Engine'];
                $tianyi_tablesnum++;
                $tianyi_tables[] = array($rs['Name'], $rs['Type'], $rs['Rows'], $this->getRealSize($rs['Data_length']), $this->getRealSize($rs['Data_free']));
            }
            else
            {
                $otherrownum += $rs['Rows'];
                $othertotalsize += ($rs['Data_length'] + $rs['Index_length'] + $rs['Data_free']);
                $rs['Type'] = isset($rs['Type']) ? $rs['Type'] : $rs['Engine'];
                $othertablenum++;
                $othertable[] = array($rs['Name'], $rs['Type'], $rs['Rows'], $this->getRealSize($rs['Data_length']), $this->getRealSize($rs['Data_free']));
            }
        }
        $tianyi_totalsize = $this->getRealSize($tianyi_totalsize);
        $othertotalsize = $this->getRealSize($othertotalsize);


        $this->_view['version'] = $database['version'];
        $this->_view['runtime'] = $database['runtime'];

        $this->_view['tianyi_tables'] = $tianyi_tables;
        $this->_view['tianyi_tablesnum'] = $tianyi_tablesnum;
        $this->_view['tianyi_rownum'] = $tianyi_rownum;
        $this->_view['tianyi_totalsize'] = $tianyi_totalsize;
        
        $this->_viewname = 'dbman';        
    }

    function PWriteFile($filename, $content, $mode = 'ab', $chmod = 1)
    {
        strpos($filename, '..') !== FALSE && exit('Access Denied!');

        $fp = @fopen($filename, $mode);
        if ($fp)
        {
            flock($fp, LOCK_EX);
            fwrite($fp, $content);
            fclose($fp);
            $chmod && @chmod($filename, 0666);
            return TRUE;
        }
        return FALSE;
    }

    function actiondbbackup()
    {
        require_once ('table.inc.php');
        require_once ('MySQL.class.php');
        $tablename = '';
        $filename = 0;
        $DB = new MySQL('localhost', 'root', 'qeephp', 'tianyi_test_new', 0);
        if(isset($_POST['checkbox_name'])){
			$name=$_POST['checkbox_name'];
			$i = 0;
            $tableid = 0;
			foreach ($name as $value){
                if($i == 0)
                { 
                    $tablename = $value;
                }
                else
                {
                    $tablename = $tablename.'|'.$value;
                }
			}
            $volume = 0;
                
            $db_prefix = 'tianyi';
            @set_time_limit(0);
            $
            $filename = 'ty'.date('YmdHis').'_'.rand()%8;

            $volume++;
            $sqlfilename = $this->_app->config('ROOT_DIR')."/static/dbak/{$filename}_{$volume}.sql";

            if ($volume == 1)
            {
                //$DB->db_query("TRUNCATE TABLE {$db_prefix}scaches");
                $tablename = implode('|', $tablename);
            }
            $sqldump = '';
            $sizelimit = 2097152;
            $tables = explode('|', $tablename);
            $currentTable = $tables[$tableid];

            $sqldump = $this->sqldumptable($tableid, $start);

            if(trim($sqldump))
            {
                $sqldump = "# tianyi Database Backup File Vol.$volume\n# Time: ".date('YmdHis')."\n# wadiff: http://wadiff.cn\n\n/*---------- SQL Dump Start ----------*/\n\n\n".$sqldump;
                if ($this->PWriteFile($sqlfilename, $sqldump, 'wb'))
                {                    
                        return $this->_redirectMessage(
                            'database_bak_process', 'file'.rawurlencode($filename).'&sizelimit='.$sizelimit.'&volume='.$volume.'&tableid='.$tableid.'&start='.$start.'&tablename='.rawurlencode($tablename),
                            url('systemsetting/backup'));
                }
                else
                {
                    return $this->_redirectMessage('database_bak_failed', $basename,
                    url('systemsetting/dbbackup'));
                }
            }
        
		}


        $query = $DB->db_query('SHOW TABLE STATUS');
        $pbtable = $othertable = array();
        while ($rs = $DB->fetch_all($query))
        {
            if (in_array($rs['Name'], $ty_tables))
            {
                $pbtable[] = array($rs['Name'], $rs['Rows'], $this->getRealSize($rs['Data_length']));
            }
            else
            {
                $othertable[] = array($rs['Name'], $rs['Rows'], $this->getRealSize($rs['Data_length']));
            }
        }

        $this->_view['tianyi_tables'] = $pbtable;
        $this->_viewname = 'dbbackup';        
    }

    function sqldumptable(&$tableid, &$start, $limit = 300)
    {
        global $DB, $sizelimit, $tables;

        //数据余量
        $sizelimit -= 300;
        $tabledump = '';
        for($count = count($tables); $tableid < $count && strlen($tabledump) < $sizelimit; $tableid++)
        {
            $table = $tables[$tableid];
            if (!$start)
            {
                //数据表结构
                $tabledump .= "DROP TABLE IF EXISTS `$table`;\n";
                $query = $DB->db_query("SHOW CREATE TABLE $table");
                $create = $DB->fetch_row($query);
                $tmpcreate = explode("\n", str_replace("\r","\n", $create[1]));
                $newcreate = '';
                foreach ($tmpcreate as $v)
                {
                    $newcreate .= trim($v);
                }
                $tabledump .= $newcreate.";\n";
            }
            $columns = $DB->fetch_one("SHOW COLUMNS FROM $table");
            while (strlen($tabledump) < $sizelimit)
            {
    //			$query = $DB->db_query($columns['Extra'] == 'auto_increment' ? "SELECT * FROM $table WHERE ".$columns['Field']." >= $start AND ".$columns['Field']." < ".($start + $limit) : "SELECT * FROM $table LIMIT $start, $limit");
                $query = $DB->db_query("SELECT * FROM $table LIMIT $start, $limit");
                if (!$DB->db_num($query))
                {
                    //单表导出完毕
                    $start = 0;
                    break;
                }
                $realrows = 0;
                $numfields = $DB->db_field_num($query);
                while ($row = $DB->fetch_row($query))
                {
                    $realrows++;
                    $comma = '';
                    $tabledump .= "INSERT INTO `$table` VALUES (";
                    for ($i = 0; $i < $numfields; $i++)
                    {
                        $tabledump .= $comma.'\''.mysql_escape_string($row[$i]).'\'';
                        $comma = ',';
                    }
                    $tabledump .= ");\n";
                    if (strlen($tabledump) >= $sizelimit)
                    {
                        //数据超过设定大小
                        $start += $realrows;
                        break 3;
                    }
                }
                $start += $limit;
            }
        }
        return $tabledump;
    }

    function splitsql($sql)
    {
        $return = array();
        $sql = str_replace("\r", "\n", $sql);
        $sql = explode(";\n", trim(substr($sql, strpos($sql, "\n\n\n"))));
        foreach($sql as $query)
        {
            $return[] = trim($query);
        }
        return $return;
    }

    function actiondbrestore()
    {
        
    }

    
    function actionLogmanagement()
    {

    }

    //用户企业信息统计功能
    function actionEnterpriseRecordCounts()
    {
        
    }    
    
    function actionEnterpriseRecordLogs()
    {
        
    }

}


